import { Card, message, Row, Col, Space, Divider, Button } from 'antd';
import { history, useRequest } from 'umi';
import { PlusOutlined } from '@ant-design/icons';
import { useState, useRef } from 'react';
import {
  ProFormSelect,
  ProFormText,
  ModalForm,
  ProFormDatePicker,
  ProFormRadio,
} from '@ant-design/pro-form';
import ProDescriptions from '@ant-design/pro-descriptions';
import type { FC } from 'react';
import ProTable from '@ant-design/pro-table';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { PageContainer } from '@ant-design/pro-layout';
import {
  addUserVisitor,
  querySubscriberDetail,
  updateUserVisitor,
  queryUserVisitorList,
} from './servic';
import { queryDictList } from '@/services/ant-design-pro/api';
import type { TableListItem, TableListPagination } from './data';

const BasicForm: FC<Record<string, any>> = () => {
  const actionRef = useRef<ActionType>();
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<TableListItem>();
  const onFinish = async (values: Record<string, any>) => {
    values.userId = history.location.query.id;
    if (currentRow) {
      values.id = currentRow.id;
      try {
        const response = await updateUserVisitor(values);
        if (response.code == 200) {
          message.success('修改成功');
          handleModalVisible(false);
          setCurrentRow(undefined);
          actionRef.current?.reloadAndRest?.();
        } else {
          message.error('修改失败!');
        }
      } catch (error) {
        console.log(error);
      }
    } else {
      try {
        const response = await addUserVisitor(values);
        if (response.code == 200) {
          message.success('提交成功');
          handleModalVisible(false);
          setCurrentRow(undefined);
          actionRef.current?.reloadAndRest?.();
        } else {
          message.error('提交失败!' + response.message);
        }
      } catch (error) {
        console.log(error);
      }
    }
  };

  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
  };

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '关系',
      dataIndex: 'relationTypeName',
    },
    {
      title: '姓名',
      dataIndex: 'visitorName',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      valueEnum: {
        1: '男',
        2: '女',
      },
    },
    {
      title: '出生日期',
      dataIndex: 'birthday',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="eidt"
          onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record);
          }}
        >
          编辑
        </a>,
      ],
    },
  ];

  return (
    <PageContainer content="">
      <Card bordered={false}>
        <ProDescriptions
          column={1}
          style={{ marginLeft: '20px' }}
          request={async () => {
            if (history.location.query.id) {
              return querySubscriberDetail(history.location.query).then(({ data }) => {
                console.log('data', data);
                return {
                  success: true,
                  data,
                };
              });
            } else {
              return {};
            }
          }}
        >
          <ProDescriptions.Item label="用户id" dataIndex="id" />
          <ProDescriptions.Item dataIndex="phone" label="用户手机号" />
          <ProDescriptions.Item label="用户昵称" dataIndex="nickName" />
        </ProDescriptions>
        <Divider />
        <ProTable<TableListItem, TableListPagination>
          actionRef={actionRef}
          rowKey="id"
          search={false}
          headerTitle="相关就诊人"
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                handleModalVisible(true);
                setCurrentRow(undefined);
              }}
            >
              <PlusOutlined /> 新增
            </Button>,
          ]}
          request={async (
            // 第一个参数 params 查询表单和 params 参数的结合
            // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
            params,
            sorter,
            filter,
          ) => {
            // console.log(params, sorter, filter);
            // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
            // 如果需要转化参数可以在这里进行修改
            let query = {
              eqQuery: {
                userId: history.location.query.id,
              },
              pageNum: params.current,
              pageSize: params.pageSize,
            };
            const msg = await queryUserVisitorList(query);
            console.log('msg', msg);
            if (msg.code == 200) {
              return {
                data: msg.data.records,
                // success 请返回 true，
                // 不然 table 会停止解析数据，即使有数据
                success: msg.message,
                // 不传会使用 data 的长度，如果是分页一定要传
                total: msg.data.total,
              };
            } else {
            }
          }}
          columns={columns}
        />
        {createModalVisible ? (
          <ModalForm
            title={currentRow ? '编辑就诊人' : '新增就诊人'}
            visible={createModalVisible}
            hideRequiredMark
            onVisibleChange={handleModalVisible}
            name="basic"
            layout="horizontal"
            initialValues={currentRow || {}}
            onFinish={onFinish}
            {...formItemLayout}
          >
            <ProFormText
              width="md"
              label="姓名"
              name="visitorName"
              rules={[
                {
                  required: true,
                  message: '请输入就诊人姓名',
                },
              ]}
              placeholder="请输入就诊人姓名"
            />
            <ProFormDatePicker
              name="birthday"
              width="md"
              rules={[
                {
                  required: true,
                  message: '请选择出生日期',
                },
              ]}
              label="出生日期"
            />
            <ProFormRadio.Group
              name="sex"
              label="性别"
              width="md"
              options={[
                {
                  label: '男',
                  value: '1',
                },
                {
                  label: '女',
                  value: '2',
                },
              ]}
            />
            <ProFormSelect
              width="md"
              name="relationType"
              label="关系"
              request={async () => {
                const params = { dictCode: 'relationType' };
                return queryDictList(params).then(({ data }) => {
                  return data.map((item) => {
                    return {
                      label: item.itemName,
                      value: item.itemValue,
                    };
                  });
                });
              }}
            />
          </ModalForm>
        ) : null}
      </Card>
    </PageContainer>
  );
};

export default BasicForm;
